package com.jpress.ejb;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.jpress.model.Tag;
import com.jpress.remote.TagRemote;

@Stateless(mappedName="bean/tag")
public class TagEJB implements TagRemote{

	@PersistenceContext(unitName="jpressEE")
	private EntityManager entityManager;
	
	@Override
	public void inserir(Tag tag) throws Exception{
		try {
			entityManager.persist(tag);
		} catch (Exception e) {
			throw e;
		}
	}

	@Override
	public void atualizar(Tag tag) throws Exception {
		try {
			entityManager.merge(tag);
		} catch (Exception e) {
			throw e;
		}
	}

	@Override
	public void excluir(Tag tag) throws Exception {
		try {
			entityManager.remove(tag);
		} catch (Exception e) {
			throw e;
		}
	}
	
	@Override
	public List<Tag> findAll() {
		Query query = entityManager.createNamedQuery("Tag.findAll");
		@SuppressWarnings("unchecked")
		List<Tag> resultado = (List<Tag>) query.getResultList();
		return resultado;
	}
	
	@Override
	public Tag findByNome(String nome) {
		Query query = entityManager.createNamedQuery("Tag.findByNome");
		query.setParameter("nome", nome);
		@SuppressWarnings("unchecked")
		List<Tag> resultado = (List<Tag>) query.getResultList();
		if (resultado.size() == 1)
			return resultado.get(0);
		return null;
	}

}
